#-*- coding: utf-8 -*-
'''
Created on Jul 14, 2012

@author: bbg
'''
import MySQLdb
import sys
import os

class DBEnv:
    def __init__(self):
        self.ins = None
        self.dbhost = '58.215.189.116:3306'
        self.dbuser = 'apkpos'
        self.dbpwd = 'apkpos'
        self.dbname = 'ap_sample'
        
    def open(self):
        try:
            self.dbcnn = MySQLdb.connect(host = self.dbhost,
                                    user = self.dbuser,
                                    passwd = self.dbpwd,
                                    db = self.dbname,
                                    charset ="utf8")
        except MySQLdb.Error, e:            
            print "error %d, %s" % (e.args[0], e.args[1])
            self.dbcnn = None
        return self.dbcnn
            
    def close(self):
        self.dbcnn.close()
        
    def fielddict(self, cursor):
        fieldsnames = {}
        i = 0
        for field in cursor.description:
            fieldsnames[field[0]] = i
            i += 1
        return fieldsnames
    
    def getCursor(self):
        return self.dbcnn.cursor()



    
if __name__ == '__main__':
    db = DBEnv()
    con = db.open()
    cursor=db.getCursor()
    n = cursor.execute("select * from CAI_NAME")    
    try:
        fields = db.fielddict(cursor)
        print "%s: " % (fields)
        row = cursor.fetchone()
        while row != None:
            print "%s:%s:%s " % (row[0],row[fields['DNBR_VAR']],row[fields['DNAM_VAR']])
            row = cursor.fetchone()                    
    finally:
        cursor.close()
        con.close()
    
    
    

    
    
    
    
    
        
        
        
